<template>
  <div>
    <div>用户信息</div>
    <button @click="asc">升序</button>
    <button @click="desc">降序</button>
    <button @click="reset">重置</button>
    <ul>
      <li v-for="(item, index) in userList" :key="index">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      userList: []
    }
  },
  // created () {

  // Promise
  //   axios
  //     .get('http://jsonplaceholder.typicode.com/users')
  //     .then((res) => {
  //       this.userList = res.data
  //     })
  //     .catch((msg) => console.log(msg))
  // }

  // async await
  async created () {
    // 解构赋值
    // 变量名与属性名不一致，中间用冒号隔开
    const { data } = await axios
      .get('http://jsonplaceholder.typicode.com/users')
    // this.userList = data
    this.proxy = new Proxy({}, {
      get (target, key) {
        if (key === 'asc') { // 升序
          // return [].concat(data).sort((a, b) => a.name > b.name ? 1 : -1)
          return [...data].sort((a, b) => a.name > b.name ? 1 : -1)
        } else if (key === 'desc') { // 降序
          // return [].concat(data).sort((a, b) => b.name > a.name ? 1 : -1)
          return [...data].sort((a, b) => b.name > a.name ? 1 : -1)
        } else {
          return data
        }
      },
      set () {
        return false
      }
    })
    this.userList = this.proxy.default
  },
  methods: {
    asc () {
      this.userList = this.proxy.asc
    },
    desc () {
      this.userList = this.proxy.desc
    },
    reset () {
      this.userList = this.proxy.default
    }
  }
}
</script>

<style>
  ul{
    padding: 0;
  }
  li{
    list-style: none;
  }
</style>
